package com.example.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.common.utls.MD5Utils;
import com.example.mybatisplus.common.utls.SessionUtils;
import com.example.mybatisplus.model.domain.User;
import com.example.mybatisplus.mapper.UserMapper;
import com.example.mybatisplus.model.dto.PageDTO;
import com.example.mybatisplus.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lj
 * @since 2024-06-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public JsonResponse login(User user) {
        // 条件构造器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, MD5Utils.md5(user.getPassword()));
        User loginUser = baseMapper.selectOne(wrapper);
        if (loginUser != null) {
            SessionUtils.saveCurrentUserInfo(loginUser);
            return JsonResponse.success(loginUser,"登录成功");
        } else {
            return JsonResponse.failure("用户名或者密码有误");
        }
    }

    @Override
    public JsonResponse pageList(User user, PageDTO pageDTO) {
        // 条件构造器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(StringUtils.isNotBlank(user.getUsername()), User::getUsername, user.getUsername())
                .eq(StringUtils.isNotBlank(user.getGender()), User::getGender, user.getGender());
        Page<User> page = this.page(new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize()), wrapper);
        return JsonResponse.success(page);
    }
}
